import React from 'react'
import Preview from './preview'
import Nav from 'app/shared/layouts/nav'
import isLoadMore from '../../loadmore.js'
import Tips from '../tips/tips'

class PreviewList extends React.Component {
  static propTypes = {
    articleGet: React.PropTypes.func,
    push: React.PropTypes.func,
    type: React.PropTypes.string,
    articleList: React.PropTypes.array
  }
  constructor() {
    super()
    this._onMineClick = this.onMineClick.bind(this)
    this.state = {
      articleList: [],
      isLoading: false,
      isNoMore: false,
      isNoMoreTmp: false
    }
    this.start = 0
    this.loadmore()
  }
  componentDidMount() {
    this.getArticleList('')
    this.setState({
      articleList: this.props.articleList
    })
  }
  getArticleList(param) {
    let self = this
    let type = this.props.type
    if (type === 'mine') {
      param += '&auther=关羽'
    }
    this.props.articleGet(param)
    setTimeout(function () {
      let data = self.props.articleList
      if (data && data.length) {
        let arr = data.concat(self.state.articleList)
        self.setState({
          isLoading: true,
          articleList: arr
        })
      } else {
        self.setState({
          isNoMore: true,
          isLoading: false
        })
      }
    }, 50)
  }
  // 我的提问
  onMineClick() {
    this.getArticleList('')
  }
  // 上拉加载
  loadmore() {
    const self = this
    let isNoMore = this.state.isNoMore
    let isNoMoreTmp = this.state.isNoMoreTmp
    window.onscroll = function () {
      if (isNoMoreTmp) {
        self.showNoMore()
        return
      }
      if (isLoadMore() && !isNoMore) {
        self.getArticleList('&_start=' + self.start)
        self.start += 10
      }
    }
  }

  render() {
    const { articleList } = this.state
    if (articleList.length === 0) {
      return (<div />)
    }
    return (
      <div>
        <Nav onMineClick={this._onMineClick} />
        {articleList.map(item => {
          return <Preview {...item} key={item.date} push={this.props.push} />
        })}
        <Tips isShow={this.state.isLoading} text='加载更多…' />
        <Tips isShow={this.state.isNoMore} text='没有更多问题了！' />
      </div>
    )
  }
}

export default PreviewList
